import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { history, type RunTimeLayoutConfig } from '@umijs/max';
import { RightContent } from '@/components';
import React, { useState, useEffect } from 'react';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import {  getUserInfo } from '@/utils/auth';
import { ConfigProvider, Result, Button } from 'antd';
import type { UserInfo } from '@/utils/auth';

const loginPath = '/login';

// 侧边栏折叠状态管理
const SidebarStateWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [collapsed, setCollapsed] = useState(() => {
    const stored = localStorage.getItem('sidebarCollapsed');
    if (stored === null) {
      localStorage.setItem('sidebarCollapsed', 'true');
      return true;
    }
    return stored === 'true';
  });

  useEffect(() => {
    localStorage.setItem('sidebarCollapsed', collapsed ? 'true' : 'false');
  }, [collapsed]);

  return React.cloneElement(children as React.ReactElement, {
    collapsed,
    onCollapse: (val: boolean) => setCollapsed(val),
  });
};

// 初始化状态（包括用户信息）
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: UserInfo;
  loading?: boolean;
  fetchUserInfo?: () => Promise<UserInfo | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const userInfo = await getUserInfo();
      return userInfo || undefined;
    } catch (error) {
      return undefined;
    }
  };

  const currentUser = await fetchUserInfo();

  return {
    fetchUserInfo,
    currentUser,
    loading: false,
    settings: defaultSettings as any,
  };
}
// 布局配置
export const layout: RunTimeLayoutConfig = ({ initialState }) => {

  const renderRightContent = () => (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
      <RightContent />
    </div>
  );

  return {
    layout: 'side',
    rightContentRender: renderRightContent,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    onPageChange: () => {
      const { pathname } = history.location;

      // 如果尝试访问登录页面，允许访问
      if (pathname === loginPath) {
        return;
      }

      // 检查用户信息，如果没有用户信息则跳转到登录页
      const userInfo = getUserInfo();
      if (!userInfo) {
        history.push(loginPath);
        return;
      }
    },
    childrenRender: (children) => {
      if (initialState?.loading) return <div>Loading...</div>;
      return (
        <ConfigProvider>
          <SidebarStateWrapper>{children}</SidebarStateWrapper>
        </ConfigProvider>
      );
    },
    ...(initialState?.settings as any),
    langMenu: false,
    unAccessible: <Result
      status="403"
      title="403"
      subTitle="Sorry, you are not authorized to access this page."
      extra={<Button type="primary" onClick={() => history.push('/')}>Back Home</Button>}
    />,
    noFound: <Result
      status="404"
      title="404"
      subTitle="Sorry, the page you visited does not exist."
      extra={<Button type="primary" onClick={() => history.push('/')}>Back Home</Button>}
    />,
    bgLayoutImgList: [],
    links: [],
    menuHeaderRender: undefined,
  };
};
// 请求配置，加入 prefix
export const request = {
  ...errorConfig,
  prefix: process.env.REACT_APP_API_URL,
  timeout: 10000,
};

